package com.mindskip.xzs.utility.excel;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * https://blog.csdn.net/jgybzx_g/article/details/118361222
 * </p>
 *
 * @author guoguangkai
 * @since 2022/6/15
 */
@Slf4j
public class EasyExcelUtil {

    private final static String DEFAULT_SHEET_NAME = "sheet1";

    /**
     * 通过模板类一次导出所有数据
     *
     * @param originalFileName  文件名，不需要加后缀，自动拼接时间
     * @param data      需要写入的数据
     * @param tempClass 模板类Class
     * @param sheetName 写入的sheet名称，不传默认是sheet1
     * @param frozenRows 标题冻结，默认0，第一行
     */
    @SneakyThrows
    public static <T> void onceExportByEntity(String originalFileName, HttpServletResponse response, List<T> data, Class<T> tempClass, String sheetName, Integer frozenRows) {
        String fileName = URLEncoder.encode(originalFileName + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMddHHmmss")), String.valueOf(StandardCharsets.UTF_8)).replaceAll("\\+", "%20");
        ExcelWriter excelWriter = null;
        OutputStream outPutStream;
        if (StringUtils.isBlank(sheetName)) {
            sheetName = DEFAULT_SHEET_NAME;
        }
        try {
            setResponse(response, fileName);
            outPutStream = response.getOutputStream();
            excelWriter = EasyExcelFactory
                    .write(outPutStream, tempClass)
                    .autoCloseStream(false)
                    //自适应设置列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .registerWriteHandler(new FreezeAndFilter(frozenRows))
                   // .registerWriteHandler(getStyleStrategy())
                    .excelType(ExcelTypeEnum.XLSX)
                    .build();
            WriteSheet sheet = EasyExcelFactory.writerSheet(sheetName).build();
            excelWriter.write(data, sheet);
        } catch (Exception e) {
            log.error("excel文件导出失败", e);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    private static void setResponse(HttpServletResponse response, String fieldName)
            throws UnsupportedEncodingException {
        String fileName = URLEncoder.encode(fieldName, String.valueOf(StandardCharsets.UTF_8));
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8));
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
    }
}
